<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';

// 创建新的axios实例用于开单API
import axios from 'axios';
const doctorAPI = axios.create({
  baseURL: 'http://localhost:5166/api',
  timeout: 10000
});

// 设置拦截器
doctorAPI.interceptors.request.use(function (config) {
  // 添加token
  config.headers["Authorization"] = "Bearer " + localStorage.getItem("token");
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 响应拦截器
doctorAPI.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  console.error('响应错误:', error);
  return Promise.reject(error);
});

// 患者信息接口
interface Patient {
  id: number;
  accountId: number;
  name: string;
  sex: boolean;
  sexText: string;
  dateOfBirth: string;
  age: number;
  contactInfo: string;
  idCard: string;
  idCardMasked: string;
  currentAddress: string;
  infectiousDiseaseHistory: string;
  geneticDiseaseInfo: string;
  createPeople: string;
  createTime: string;
  updatePeople: string;
  updateTime: string;
}

// 定义药品接口
interface Drug {
  id: number;
  categoryId: number;
  categoryName: string;
  drugName: string;
  dosage: string;
  efficacy: string;
  price: number;
  isPrescription: boolean;
  limitQuantity: number;
  imageUrl: string;
}

// 定义检查项目接口
interface CheckupItem {
  id: number;
  categoryId: number;
  categoryName: string;
  itemName: string;
  price: number;
  notes: string;
}

// 定义检验项目接口
interface TestItem {
  id: number;
  categoryId: number;
  categoryName: string;
  itemName: string;
  price: number;
}

// 购物车项目接口
interface CartItem {
  drug?: Drug;
  checkupItem?: CheckupItem;
  testItem?: TestItem;
  quantity: number;
}

// 处方明细接口
interface PrescriptionDetail {
  itemType: number;
  itemId: number;
  quantity: number;
  unitPrice: number;
  amount: number;
}

const router = useRouter();
// const route = useRoute(); // 暂时未使用，注释掉

// 状态变量
const selectedItems = ref<CartItem[]>([]);
const patients = ref<Patient[]>([]);
const selectedPatient = ref<Patient | null>(null);
const showPatientPopup = ref(false);
const showSuccessPopup = ref(false); // 成功弹窗控制
const applyReason = ref('');
const hospital = ref('');
const characterCount = ref(0);
const maxCharacters = 200;
const minCharacters = 20;

// 计算总价
const totalPrice = computed(() => {
  const total = selectedItems.value.reduce((sum, item) => {
    if (item.drug) {
      return sum + item.drug.price * item.quantity;
    } else if (item.checkupItem) {
      return sum + item.checkupItem.price * item.quantity;
    } else if (item.testItem) {
      return sum + item.testItem.price * item.quantity;
    }
    return sum;
  }, 0);
  return total.toFixed(2);
});

// 获取患者列表
const fetchPatients = async () => {
  try {
    const accountId = localStorage.getItem('userId') || '1';
    // 使用正确的API路径
    const response = await axiosrnewmedical.get(`/Patient/GetPatientByAccountId`, {
      params: { accountId: accountId }
    });
    
    if (response.data.code === 200 && response.data.data) {
      patients.value = Array.isArray(response.data.data) 
        ? response.data.data 
        : [response.data.data];
      
      if (patients.value.length > 0) {
        selectedPatient.value = patients.value[0];
      }
    } else {
      console.error('获取患者列表失败:', response.data.msg);
      // 添加示例数据
      patients.value = [
        {
          id: 1,
          accountId: 1,
          name: '王小珂',
          sex: true,
          sexText: '男',
          dateOfBirth: '1990-01-01',
          age: 33,
          contactInfo: '13800138000',
          idCard: '510122199001010000',
          idCardMasked: '2015*****10',
          currentAddress: '四川省成都市',
          infectiousDiseaseHistory: '',
          geneticDiseaseInfo: '',
          createPeople: '',
          createTime: '',
          updatePeople: '',
          updateTime: ''
        },
        {
          id: 2,
          accountId: 1,
          name: '李玲玲',
          sex: false,
          sexText: '女',
          dateOfBirth: '1995-01-01',
          age: 28,
          contactInfo: '13900139000',
          idCard: '510122199501010000',
          idCardMasked: '2015*****10',
          currentAddress: '四川省成都市',
          infectiousDiseaseHistory: '',
          geneticDiseaseInfo: '',
          createPeople: '',
          createTime: '',
          updatePeople: '',
          updateTime: ''
        }
      ];
      
      if (patients.value.length > 0) {
        selectedPatient.value = patients.value[0];
      }
    }
  } catch (error) {
    console.error('获取患者列表请求错误:', error);
    // 添加示例数据
    patients.value = [
      {
        id: 1,
        accountId: 1,
        name: '王小珂',
        sex: true,
        sexText: '男',
        dateOfBirth: '1990-01-01',
        age: 33,
        contactInfo: '13800138000',
        idCard: '510122199001010000',
        idCardMasked: '2015*****10',
        currentAddress: '四川省成都市',
        infectiousDiseaseHistory: '',
        geneticDiseaseInfo: '',
        createPeople: '',
        createTime: '',
        updatePeople: '',
        updateTime: ''
      }
    ];
    
    if (patients.value.length > 0) {
      selectedPatient.value = patients.value[0];
    }
  }
};

// 选择患者
const selectPatient = (patient: Patient) => {
  selectedPatient.value = patient;
  showPatientPopup.value = false;
};

// 监听申请原因变化
const handleReasonChange = (event: Event) => {
  const target = event.target as HTMLTextAreaElement;
  applyReason.value = target.value;
  characterCount.value = target.value.length;
};

const goBack = () => {
  router.back();
};

// 提交申请
const submitApplication = async () => {
  if (!selectedPatient.value) {
    alert('请选择就诊人');
    return;
  }
  
  if (applyReason.value.length < minCharacters) {
    alert(`申请原因不能少于${minCharacters}个字`);
    return;
  }
  
  // 构建处方明细
  const prescriptionDetails: PrescriptionDetail[] = [];
  selectedItems.value.forEach(item => {
    if (item.drug) {
      const quantity = item.quantity || 1;
      const unitPrice = item.drug.price;
      prescriptionDetails.push({
        itemType: 1, // 药品类型
        itemId: item.drug.id,
        quantity: quantity,
        unitPrice: unitPrice,
        amount: unitPrice * quantity
      });
    } else if (item.checkupItem) {
      const quantity = 1; // 检查项目默认数量为1
      const unitPrice = item.checkupItem.price;
      prescriptionDetails.push({
        itemType: 2, // 检查类型
        itemId: item.checkupItem.id,
        quantity: quantity,
        unitPrice: unitPrice,
        amount: unitPrice * quantity
      });
    } else if (item.testItem) {
      const quantity = 1; // 检验项目默认数量为1
      const unitPrice = item.testItem.price;
      prescriptionDetails.push({
        itemType: 3, // 检验类型
        itemId: item.testItem.id,
        quantity: quantity,
        unitPrice: unitPrice,
        amount: unitPrice * quantity
      });
    }
  });
  
  // 计算总金额，确保与明细金额一致
  const totalAmount = prescriptionDetails.reduce((sum, item) => sum + item.amount, 0);
  
  const requestData = {
    hospitalId: Number(localStorage.getItem('hospitalId')) || 1, // 医院ID，默认为1
    userId: selectedPatient.value.id,
    applyReason: applyReason.value,
    totalAmount: totalAmount, // 添加总金额
    auditorId: 1, // 默认为1
    details: prescriptionDetails
  };

  console.log('提交数据:', JSON.stringify(requestData));

  try {
    // 使用正确的API路径和端口
    const response = await doctorAPI.post('/doctor/Prescription/CreatePrescription', requestData);
    if (response.data.code === 200) {
      // 保存申请ID到localStorage，供支付页面使用
      if (response.data.data && response.data.data.id) {
        localStorage.setItem('currentPrescriptionApplicationId', response.data.data.id.toString());
        console.log('申请创建成功，申请ID:', response.data.data.id);
      }
      
      // 显示成功弹窗
      showSuccessPopup.value = true;
    } else {
      alert('开单申请提交失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('开单申请提交错误:', error);
    alert('开单申请提交失败，请稍后再试');
  }
};

// 跳转到开单记录页面
const goToRecords = () => {
  router.push('/prescription-record');
};

onMounted(() => {
  // 从localStorage获取选择的项目
  const storedItems = localStorage.getItem('selectedItems');
  if (storedItems) {
    selectedItems.value = JSON.parse(storedItems);
  }

  // 从localStorage获取医院信息
  const hospitalId = localStorage.getItem('hospitalId');
  const hospitalName = localStorage.getItem('hospitalName');
  if (hospitalId && hospitalName) {
    hospital.value = hospitalName;
  } else {
    hospital.value = '四川省保健院北苑';
  }

  // 获取患者列表
  fetchPatients();
});
</script>

<template>
  <div class="order-confirm-page">
    <van-nav-bar
      title="开单确认"
      left-arrow
      @click-left="goBack"
    />

    <div class="info-section">
      <div class="section-title">申请信息</div>
      <div class="info-item">
        <div class="info-label">申请医院</div>
        <div class="info-value">{{ hospital }}</div>
      </div>
      <div class="info-item" @click="showPatientPopup = true">
        <div class="info-label">申请人</div>
        <div class="info-value">
          {{ selectedPatient?.name || '未选择' }}
          <span class="patient-id-card" v-if="selectedPatient?.idCardMasked">{{ selectedPatient?.idCardMasked }}</span>
          <van-icon name="arrow" />
        </div>
      </div>
    </div>

    <div class="reason-section">
      <div class="section-title">申请原因<span class="required">*</span></div>
      <div class="reason-input">
        <textarea 
          v-model="applyReason" 
          placeholder="请输入项目申请原因用于医生更准确判断，不少于20字"
          @input="handleReasonChange"
        ></textarea>
        <div class="character-count">{{ characterCount }} / {{ maxCharacters }}</div>
      </div>
    </div>

    <div class="items-section">
      <div class="section-title">申请项目</div>
      <div class="items-list">
        <!-- 药品项目 -->
        <div v-for="(item, index) in selectedItems.filter(i => i.drug)" :key="`drug-${index}`" class="order-item">
          <div class="item-type">药</div>
          <div class="item-content">
            <div class="item-name">{{ item.drug?.drugName }}</div>
            <div class="item-info">
              <span class="item-price">￥{{ item.drug?.price.toFixed(2) }}/剂</span>
              <span class="item-quantity">数量: {{ item.quantity }}剂</span>
            </div>
            <div class="item-tags">
              <span class="tag prescription" v-if="item.drug?.isPrescription">处方药</span>
              <span class="tag limit" v-if="item.drug?.limitQuantity">限购{{ item.drug?.limitQuantity }}剂</span>
            </div>
          </div>
        </div>

        <!-- 检查项目 -->
        <div v-for="(item, index) in selectedItems.filter(i => i.checkupItem)" :key="`checkup-${index}`" class="order-item">
          <div class="item-type check">查</div>
          <div class="item-content">
            <div class="item-name">{{ item.checkupItem?.itemName }}</div>
            <div class="item-info">
              <span class="item-price">￥{{ item.checkupItem?.price.toFixed(2) }}/次</span>
            </div>
          </div>
        </div>

        <!-- 检验项目 -->
        <div v-for="(item, index) in selectedItems.filter(i => i.testItem)" :key="`test-${index}`" class="order-item">
          <div class="item-type test">验</div>
          <div class="item-content">
            <div class="item-name">{{ item.testItem?.itemName }}</div>
            <div class="item-info">
              <span class="item-price">￥{{ item.testItem?.price.toFixed(2) }}/次</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <div class="footer-content">
        <div class="total-price">合计: <span class="price">￥{{ totalPrice }}</span></div>
        <button class="submit-btn" @click="submitApplication">确认申请</button>
      </div>
    </div>

    <!-- 患者选择弹窗 -->
    <van-popup v-model:show="showPatientPopup" position="bottom" round :style="{ height: '45%' }">
      <div class="patient-popup">
        <div class="popup-header">
          <div class="popup-title">选择就诊人</div>
          <van-icon name="cross" @click="showPatientPopup = false" />
        </div>
        <div class="popup-content">
          <div 
            v-for="patient in patients" 
            :key="patient.id" 
            class="patient-item"
            @click="selectPatient(patient)"
          >
            <div class="patient-name">{{ patient.name }}</div>
            <div class="patient-id">{{ patient.idCardMasked }}</div>
          </div>
        </div>
        <div class="popup-footer">
          <button class="add-patient-btn">添加就诊人</button>
        </div>
      </div>
    </van-popup>

    <!-- 成功弹窗 -->
    <van-popup v-model:show="showSuccessPopup" position="center" round :style="{ width: '80%' }">
      <div class="success-popup-content">
        <div class="success-title">申请提示</div>
        <div class="success-message">
          项目申请已提交，请耐心等待审核结果，可在开单记录中查询审核状态
        </div>
        <button class="success-btn" @click="goToRecords">去查看</button>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.order-confirm-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

.info-section, .reason-section, .items-section {
  background: white;
  margin-bottom: 10px;
  padding: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
}

.required {
  color: #f56c6c;
  margin-left: 3px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 15px;
  color: #666;
}

.info-value {
  font-size: 15px;
  color: #333;
  display: flex;
  align-items: center;
}

.patient-id-card {
  font-size: 14px;
  color: #999;
  margin-left: 5px;
}

.reason-input {
  position: relative;
}

textarea {
  width: 100%;
  height: 120px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
  font-size: 15px;
  color: #333;
  resize: none;
  background-color: #f9f9f9;
}

.character-count {
  position: absolute;
  bottom: 10px;
  right: 10px;
  font-size: 14px;
  color: #999;
}

.items-list {
  margin-bottom: 10px;
}

.order-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-type {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1989fa;
  color: white;
  border-radius: 4px;
  font-size: 14px;
  font-weight: bold;
  margin-right: 12px;
}

.item-type.check {
  background-color: #07c160;
}

.item-type.test {
  background-color: #ff9900;
}

.item-content {
  flex: 1;
}

.item-name {
  font-size: 16px;
  margin-bottom: 6px;
}

.item-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.item-price {
  font-size: 15px;
  color: #f56c6c;
}

.item-quantity {
  font-size: 14px;
  color: #666;
}

.item-tags {
  display: flex;
  gap: 8px;
}

.tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #e6f0ff;
}

.prescription {
  color: #1989fa;
}

.limit {
  color: #ff9900;
  background-color: #fff9e6;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 12px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.footer-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.total-price {
  font-size: 16px;
  font-weight: 500;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.submit-btn {
  width: 90%;
  max-width: 320px;
  background-color: #1989fa;
  color: white;
  border: none;
  padding: 12px 0;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
}

/* 患者选择弹窗 */
.patient-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.popup-title {
  font-size: 18px;
  font-weight: 500;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.patient-item {
  padding: 15px;
  background-color: #f5f9ff;
  margin: 10px 15px;
  border-radius: 8px;
  cursor: pointer;
}

.patient-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 5px;
}

.patient-id {
  font-size: 14px;
  color: #999;
}

.popup-footer {
  padding: 15px;
  border-top: 1px solid #f5f5f5;
}

.add-patient-btn {
  width: 100%;
  background-color: #1989fa;
  color: white;
  border: none;
  border-radius: 25px;
  padding: 12px 0;
  font-size: 16px;
  cursor: pointer;
}

/* 成功弹窗 */
.success-popup-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 25px 20px;
}

.success-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.success-message {
  font-size: 15px;
  color: #666;
  text-align: center;
  margin-bottom: 25px;
  line-height: 1.6;
}

.success-btn {
  width: 100%;
  max-width: 200px;
  background-color: #1989fa;
  color: white;
  border: none;
  padding: 10px 0;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
}
</style> 